<?php

namespace App\Http\Controllers\App\Attachment;

use App\Http\Controllers\Controller;
use App\Models\Attachment;
use Illuminate\Support\Facades\Storage;

class AttachmentController extends Controller
{
    /**
     * @OA\Get(path="/attachment",tags={"附件"},summary="列表",
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function index()
    {
        if ($this->request->ajax()) {
            $param = $this->request->all();
            $where = [];
            if (!empty($param['id'])) {
                $where[] = ['id', '=', $param['id']];
            }
            if (!empty($param['user_id'])) {
                $where[] = ['user_id', '=', $param['user_id']];
            }
            if (!empty($param['file_name'])) {
                $where[] = ['file_name', 'like', '%' . $param['file_name'] . '%'];
            }
            if (!empty($param['file_type'])) {
                $where[] = ['file_type', '=', $param['file_type']];
            }
            if (!empty($param['file_path'])) {
                $where[] = ['file_path', '=', $param['file_path']];
            }
            $list = Attachment::where($where)->orderBy('id', 'desc')->paginate(10);
            return [
                'code'    => 0,
                'message' => 'success',
                'count'   => $list->total(),
                'data'    => $list->items()
            ];
        }
        return view('app.attachment.image');
    }

    /**
     * @OA\Post(path="/attachment",tags={"附件"},summary="添加",
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="路径", property="path", type="string", default=""),
     *           @OA\Property(description="文件", property="file", type="resource", default=""),required={"file"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function save()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('file为空');
        }
        $type              = $this->request->param('file_type', 'image');
        $type              = in_array($type, ['image', 'file', 'video', 'audio']) ? $type : 'image';
        $data['user_id']   = $this->user_id;
        $data['file_name'] = $file->getOriginalName();
        $data['file_md5']  = $file->md5();
        $data['file_sha1'] = $file->sha1();
        $data['file_ext']  = $file->extension();
        $data['file_size'] = $file->getSize();
        $data['file_type'] = $type;

        // 判断文件记录
//        $config            = Config::get('filesystem');
//        $file_info = File::where(['user_id' => $data['user_id'], 'file_sha1' => $data['file_sha1']])->find();
//        if ($file_info) {
//            $file_info['file_path'] = $config['disks'][$config['default']]['url'] . $file_info['file_path'];
//            return $this->success('文件上传成功', $file_info);
//        }

        dd($data);
        // 本地存储
        Storage::disk('local')->put('example.txt', 'Contents');
        $save_name = Filesystem::disk('public')->putFile($type, $file);
        if (!$save_name) {
            $this->error('文件上传失败');
        }
        $data['file_path'] = str_replace("\\", "/", $save_name);

        // 云存储
        //$data = Attachment::putFile($data['file_path']);
        //if ($data['code']) {
        //    $this->error($data['code']);
        //}
        $data['file_path'] = $this->request->domain() . '/storage/' . $data['file_path'];

        $result = Attachment::create($data);
        if (!$result) {
            $this->error('文件保持失败');
        }
        $result->src = $result->file_path;
        $this->success('文件上传成功', $result);
    }

    /**
     * 显示指定的资源
     *
     * @param string $file_path
     * @return array
     */
    public function read($file_path)
    {
        return Attachment::where('user_id', $this->user_id)->where('file_path', $file_path)->find();
    }

    /**
     * @OA\Delete(path="/attachment",tags={"附件"},summary="删除",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="路径", property="file_path", type="string", default=""),required={"file_path"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function delete()
    {
        $config    = Config::get('filesystem');
        $file_path = $this->request->post('file_path');
        $file_path = str_replace($config['disks'][$config['default']]['url'], '', $file_path);
        $file      = $this->read($file_path);
        if (!$file) {
            return $this->success('删除成功');
        }
        // 云存储
        Attachment::deleteFile($file['file_path']);

        unlink($config['disks']['public']['root'] . '/' . $file['file_path']);
        $result = Attachment::where('file_path', $file_path)->delete();
        if ($result) {
            return $this->success('删除成功');
        }
        return $this->error('删除失败');
    }
}
